package com.hongning.railway.ui.categorylistnews;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.hongning.railway.BR;
import com.hongning.railway.R;
import com.hongning.railway.app.AppViewModelFactory;
import com.hongning.railway.app.Constant;
import com.hongning.railway.databinding.FragmentDetailBinding;
import com.hongning.railway.entity.LoginEntity;
import com.hongning.railway.entity.reqbean.ReqAddScoreBean;
import com.hongning.railway.entity.resbean.ResDynamicBean;
import com.hongning.railway.entity.resbean.ResNewsBean;
import com.hongning.railway.entity.resbean.ResVideoBean;
import com.hongning.railway.util.Apputils;
import com.zzhoujay.richtext.RichText;

import java.util.HashMap;
import java.util.Map;

import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.bus.Messenger;

/**
 * Author: zhangjing
 * DATA:2019-08-14 15:51
 * DESC:
 * email:zhangjingworkmol@163.com
 */
public class NewDetailFragment extends BaseFragment<FragmentDetailBinding,NewDetailFragmentViewModel> {
    public static final String NEWS_INFO = "news_info";
    Object mResNewsBean;
    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_detail;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }


    @Override
    public NewDetailFragmentViewModel initViewModel() {
        AppViewModelFactory appViewModelFactory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this,appViewModelFactory).get(NewDetailFragmentViewModel.class);
    }

    @Override
    public void initParam() {
        super.initParam();
        mResNewsBean = getArguments().getParcelable(NEWS_INFO);

    }

    @Override
    public void initData() {
        initWebSetting();
//        binding.webContent.setWebChromeClient(new WebChromeClient(){
//
//        });
        binding.webContent.setWebViewClient(new WebViewClient(){
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                Map extraHeaders = new HashMap();
                LoginEntity loginEntity = Apputils.getLoginInfo();
                if (loginEntity!=null){
                    extraHeaders.put("token",loginEntity.getToken());
                }
                view.loadUrl(request.getUrl().toString(),extraHeaders);
                return false;
            }
        });
        super.initData();
        if (mResNewsBean==null)return;
        binding.layoutIncludeTitle.ivLeft.setVisibility(View.VISIBLE);
        binding.layoutIncludeTitle.ivLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
        if (mResNewsBean instanceof ResNewsBean){
            binding.layoutIncludeTitle.tvTopTitle.setText("资讯详情");
            viewModel.requestDetail(((ResNewsBean)mResNewsBean).getNewsId());
            binding.tvTitle.setText(((ResNewsBean) mResNewsBean).getNewsTitle());
        }else if (mResNewsBean instanceof ResDynamicBean.DataBean){
            binding.layoutIncludeTitle.tvTopTitle.setText("动态详情");
            viewModel.requestDetail(((ResDynamicBean.DataBean)mResNewsBean).getNewsId());
            binding.tvTitle.setText(((ResDynamicBean.DataBean) mResNewsBean).getNewsTitle());
        }else if (mResNewsBean instanceof ResVideoBean){
            binding.layoutIncludeTitle.tvTopTitle.setText("课程详情");
            viewModel.requestDetail(((ResVideoBean)mResNewsBean).getNewsId());
            binding.tvTitle.setText(((ResVideoBean) mResNewsBean).getNewsTitle());
            Messenger.getDefault().sendNoMsg(Constant.LESSON_REFRESH);
        }
        ReqAddScoreBean reqAddScoreBean = new ReqAddScoreBean();
        reqAddScoreBean.setProjectId("001001001002");
        Messenger.getDefault().send(reqAddScoreBean,Constant.ADD_SCORE);

    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.uc.content.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
//                String pre = "<style>img { display: block; width: 100% }* { padding: 0px; margin: 0px }</style>";
                String pre = "<style>img { display: block; width: 100%; height: auto }* { padding: 0px; margin: 0px }</style>";
                binding.webContent.loadDataWithBaseURL(null,pre+s,"text/html", "utf-8", null);

//                binding.webContent.loadUrl("https://h5.devtest.haifu365.com/#/");
//
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RichText.clear(getActivity());

    }

    void  initWebSetting(){
        WebSettings webSetting = binding.webContent.getSettings();

        webSetting.setDatabaseEnabled(true);
        webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSetting.setTextSize(WebSettings.TextSize.NORMAL);

        // ===设置JS可用
        webSetting.setJavaScriptEnabled(true);
        // JS打开窗口
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        // ===设置JS可用
        // 可以访问文件
        webSetting.setAllowFileAccess(true);
        // ===缩放可用
        webSetting.setSupportZoom(true);
        webSetting.setDisplayZoomControls(false); //隐藏原生的缩放控件
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS); //设置缩放功能   //能不能缩放 取决于网页设置
        webSetting.setLoadWithOverviewMode(false);
        webSetting.setBuiltInZoomControls(true);
        // ===缩放可用
        // 支持多窗口
        webSetting.setSupportMultipleWindows(true);
        // ===============缓存
        webSetting.setCacheMode(WebSettings.LOAD_DEFAULT);// 决定是否从网络上取数据。
        webSetting.setAppCacheEnabled(true);
        // ===============缓存
        webSetting.setUseWideViewPort(false);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // ==定位
        webSetting.setDomStorageEnabled(true);
        webSetting.setGeolocationEnabled(true);

//        LoginEntity loginEntity = Apputils.getLoginInfo();
    }
}
